package ph.gov.marikina.mcsmtms.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ph.gov.marikina.mcsmtms.dao.DAO;
@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
public class BaseHibernateDAO<E, K extends Serializable> implements DAO {
	private SessionFactory sessionFactory;
	private Class<? extends E> daoType;
	
	@SuppressWarnings("unchecked")
	public BaseHibernateDAO() {
		daoType = (Class<E>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	protected Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	public void add(E entity){
		getCurrentSession().save(entity);
	}
	
	public void update(E entity){
		getCurrentSession().saveOrUpdate(entity);
	}
	
	public void remove(E entity){
		getCurrentSession().delete(entity);
	}
	
	@SuppressWarnings("unchecked")
	public E find(K key){
		return (E) getCurrentSession().get(daoType, key);
	}
	
	@SuppressWarnings("unchecked")
	public List<E> list(){
		return getCurrentSession().createCriteria(daoType).list();
	}

}
